$(function () {
    //Demo
    layui.use('form', function(){
        var form = layui.form;

        //监听提交
        form.on('submit(formDemo)', function(data){
            layer.msg(JSON.stringify(data.field));
            return false;
        });
    });

    layui.use('layer', function(){
        var layer = layui.layer;
    });

   
    //加载供应商下拉框
    showAllSup();
    //加载登录用户
    showLoginUser();
})

function checkName(numberObj) {
    var obj =$(numberObj).val()
    var str = ""
    var regexp = new RegExp(/^[a-zA-Z0-9\u4e00-\u9fa5]{2,}$/)
    if(!regexp.test(obj.toString())){
        str += "名称必须是两位以上的汉字字母数字组合"
    }
    if(str.length == 0 ){
        $(numberObj).next("span").html("✔").css("color","green")
    }else {
        $(numberObj).next("span").html(str).css("color","red")
    }
}

function checkNumber(numberObj) {
    var obj =$(numberObj).val()
    var regexp = new RegExp(/^[1-9]\d*$/)
    var  str = ""
    if(!regexp.test(obj.toString())){
        str +="数字必须为正整数"
    }
    if(str.length == 0 ){
        $(numberObj).next("span").html("✔").css("color","green")
    }else {
        $(numberObj).next("span").html(str).css("color","red")
    }
}

// function check() {
//     $("#f1 input").blur(function () {
//         // alert($(this).val())
//         var  str = $(this).val()
//         if(str.length == 0){
//           $(this).next("span").html("内容不能为空").css("color","red")
//         }
//         else {
//             $(this).next("span").html("ok").css("color","green")
//
//         }
//     })
// }


//添加弹出层
function showAdd() {
    $("#f1")[0].reset()
    var list =  $("#f1 span[name='check']")
    for(var i = 0;i<list.length;i++){
        $(list[i]).html("")
    }
    layer.open({
        title:"添加采购商品", //标题
        type:1,//弹出层类别，1表示页面层
        shadeClose:true,//点击遮罩关闭
        skin:'layui-layer-rim',//加上边框
        area:['620px','500px'],//宽高
        anim:1,
        content:$("#formDiv")
    });
    $("#picture").attr("src","../img/start.jpg")
}

//下拉框显示所有供应商
function showAllSup() {
    $.post("/buy/findAllSup",null,function (supList) {
        var str = "";
        for(var i = 0; i< supList.length;i++){
            var obj = supList[i];
            str += `<option value="${obj.id}">${obj.name}</option>`
        }
        $("#sup").html(str)
    })
}

//按照供应商下拉框显示采购物品
function showBySup() {
    var supId=$("#sup").val()
    $.post("/buy/findBySup","&supId="+supId,function (list) {
        var str = "";
        for(var i = 0 ; i <list.length;i++){
            var obj = list[i]
            str += `<tr><td>${obj.product.name}</td>
                            <td>${obj.product.vender}</td>
                            <td>${obj.product.buyPrice}</td>
                            <td>${obj.product.sellPrice}</td>
                            <td><input type="text" value="${obj.num}" id="number" onblur="updateNum(${obj.product.id})"></td>
                            <td><a class="layui-btn layui-btn-danger" href="javascript:del(${obj.product.id})">移除商品</a></td></tr>`
        }
        $("#productData").html(str)
    })
}


//失去购物车焦点后修改数量
function updateNum(proId) {
    var supId=$("#sup").val()
    var number = $("#number").val()
    $.post("/buy/updateNum","&supId="+supId+"&proId="+proId+"&number="+number,function () {
        
    })
}
//按商品id删除商品
function del(productId) {
    var supId=$("#sup").val()
    // alert(supId)
 $.post("/buy/remove","&productId="+productId+"&supId="+supId,function (info) {
     if(info == "ok"){
         showBySup();
     }
 })
}


function showLoginUser() {
    
    $.post("/user/getUser",null,function (userObj) {
        $("#user").html(userObj.name)
    })
}

function  layuiCheck() {
    var list =  $("#f1 span[name='check']")
    for(var i = 0;i<list.length;i++){
        if($(list[i]).html() != "✔"){
            return false;
        }
    }
    return true;
}

//添加商品
function addProduct() {
    $("#img").attr("disabled",false)
    checkNumber($("#proId"))
    checkName($("#proName"))
    checkName($("#vender"))
    checkNumber($("#buyPrice"))
    checkNumber($("#sellPrice"))
    checkNumber($("#num"))
    if(!layuiCheck()){
        layer.msg("数据格式错误")
        return
    }
        var formData = new FormData($("#f1")[0]);
        $.ajax({
            url: '/buy/add' ,
            type: 'POST',
            data: formData,
            // dataType:"json",
            contentType: false,
            processData: false,
            success: function (info) {
                showBySup()
            }
        });
        layer.closeAll();
    $("#f1")[0].reset()
}

//预览图片
function upLoad(Obj){
    var file = Obj.files[0];
    var reader = new  FileReader();
    reader.readAsDataURL(file);
    reader.onload = function (ev) {
        $("#picture").attr("src", ev.target.result);
    }
}

//自动更新弹出框
function renderForm() {
    layui.use('form', function() {
        var form = layui.form; //高版本建议把括号去掉，有的低版本，需要加()
        form.render();
    });
}
// 当添加框的编号栏失去焦点，查询是否有该商品并显示在弹出框中
function abc() {
    // checkNumber(numberObj)


    var proId = $("#proId").val();
    if(proId.length == 0){
        $("#proName")[0].readOnly=''
        $("#vender")[0].readOnly=''
        $("#buyPrice")[0].readOnly=''
        $("#sellPrice")[0].readOnly=''
        $("#type").attr("disabled",false)
        $("#img").attr("disabled",false)
        $("#f1")[0].reset()
        return
    }
    $.post("/product/onblur","&proId="+proId,function (product) {
        if(product.length == 0){
            $("#f1")[0].reset()
            $("#proId").val(proId)
            $("#method").val("add")
            var supId=$("#sup").val()
            $("#sup1").val(supId)
            $("#proName")[0].readOnly=''
            $("#vender")[0].readOnly=''
            $("#buyPrice")[0].readOnly=''
            $("#sellPrice")[0].readOnly=''
            $("#type").attr("disabled",false)
            $("#img").attr("disabled",false)
            $("#picture").attr("src","../img/start.jpg")
            renderForm()
        }else {
            $("#f1")[0].reset()
            $("#proId").val(proId)
            $("#proName").val(product.name)
            $("#proName")[0].readOnly='readOnly'
            $("#vender").val(product.vender)
            $("#vender")[0].readOnly='readOnly'
            $("#buyPrice").val(product.buyPrice)
            $("#buyPrice")[0].readOnly='readOnly'
            $("#sellPrice").val(product.sellPrice)
            $("#sellPrice")[0].readOnly='readOnly'
            let type = product.type.toString()
            $("#type").find("option:contains('"+type+"')").attr("selected",true)
            $("#type").attr("disabled",true)
            var supId=$("#sup").val()
            $("#sup1").val(supId)
            $("#method").val("notadd")
            $("#picture").attr("src","../img/"+product.photo.toString())
            $("#img")[0].disabled='disabled'
            renderForm()
        }
    })
}

//商品入库
function buy() {
    var supId = $("#sup").val();
    var userName = $("#user").html()
    $.post("/buy/sureBuy","&supId="+supId+"&userName="+userName,function (info) {
        if(info == "ok"){
            alert("入库成功")
            showBySup();
        }
    })
}
